package com.puccampinas.finalproject.rest;

import java.util.ArrayList;
import java.util.Date;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;

import com.eaio.uuid.UUID;
import com.google.gson.Gson;
import com.puccampinas.finalproject.core.controller.UserController;
import com.puccampinas.finalproject.core.persistence.entity.Message;
import com.puccampinas.finalproject.core.persistence.entity.MessageList;
import com.puccampinas.finalproject.rest.to.RequestResponse;
import com.puccampinas.finalproject.rest.to.ResponseStatus;

@Path("/api/services")
public class ServiceHandler {


	@GET
    @Path("geolocation/")
    @Produces({MediaType.APPLICATION_JSON})
	public String geolocation(@QueryParam("usuario") Long usuario, @QueryParam("longitude") String longitude, @QueryParam("latitude") String latitude, @QueryParam("callback") String callback) {
		
		String ticket = new UUID().toString();
		RequestResponse rp = new RequestResponse();
		rp.setTicket(ticket);
		rp.setDate(new Date());
		rp.setStatus(ResponseStatus.ERROR);
		rp.setMessage("ERRO AO SALVAR POSICAO");
		
		if (usuario != null && StringUtils.isNotEmpty(longitude) && StringUtils.isNotEmpty(latitude)) {
			Boolean result = UserController.salvarCoordenadas(usuario, latitude, longitude);
			if (result) {
				rp.setStatus(ResponseStatus.OK);
				rp.setMessage("POSICAO SALVA COM SUCESSO");
			}
		} 
		
		Gson gson = new Gson();
		String json = gson.toJson(rp);
		
		return callback + "(" + json + ")";
	}
	
	@GET
    @Path("messages/")
    @Produces({MediaType.APPLICATION_JSON})
	public String messages(@QueryParam("usuario") Long usuario, @QueryParam("callback") String callback) {
		MessageList messageList = new MessageList();
		messageList.setMessages(new ArrayList<Message>());
		
		if (usuario != null) {
			messageList.getMessages().addAll(UserController.obterMensagens(usuario));
			messageList.setQtdMessages(messageList.getMessages().size());
		} 
		
		Gson gson = new Gson();
		String json = gson.toJson(messageList);
		
		return callback + "(" + json + ")";
	}

}
